#!/bin/bash
#
# sanlock - SAN-based lock manager
#
# chkconfig: 2345 97 03
# description: starts and stops sanlock daemon
#


### BEGIN INIT INFO
# Provides: sanlock
# Required-Start: $time $syslog wdmd
# Required-Stop: $syslog
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts and stops sanlock daemon
# Description: starts and stops sanlock daemon
### END INIT INFO

. /etc/rc.d/init.d/functions

prog="sanlock"
runfile="/run/$prog/$prog.pid"
lockfile="/var/lock/subsys/$prog"
exec="/usr/sbin/$prog"

SANLOCKUSER="sanlock"
SANLOCKOPTS="-U $SANLOCKUSER -G $SANLOCKUSER"

[ -f /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

start() {
	[ -x $exec ] || exit 5

	if [ ! -d /run/$prog ]; then
		install -d -o $SANLOCKUSER -g $SANLOCKUSER -m 775 /run/$prog
		[ -x /sbin/restorecon ] && restorecon /run/$prog
	fi

	echo -n $"Starting $prog: "
	daemon $prog daemon $SANLOCKOPTS
	retval=$?
	echo
	[ $retval -eq 0 ] && touch $lockfile
	return $retval
}

stop() {
	PID=$(pidofproc -p $runfile $prog)

	echo -n $"Sending stop signal $prog ($PID): "
	killproc -p $runfile $prog -TERM
	retval=$?
	echo

	if [ $retval -ne 0 ]; then
		return $retval
	fi

	echo -n $"Waiting for $prog ($PID) to stop:"

	timeout=10
	while checkpid $PID; do
		sleep 1
		timeout=$((timeout - 1))
		if [ "$timeout" -le 0 ]; then
			failure; echo
			return 1
		fi
	done

	success; echo
	rm -f $lockfile
	return $retval
}

restart() {
	rh_status_q && stop
	start
}

reload() {
	restart
}

rh_status() {
	status $prog
}

rh_status_q() {
	rh_status >/dev/null 2>&1
}

case "$1" in
	start)
		rh_status_q && exit 0
		$1
		;;
	stop)
		rh_status_q || exit 0
		$1
		;;
	restart)
		$1
		;;
	reload)
		rh_status_q || exit 7
		$1
		;;
	force-reload)
		force_reload
		;;
	status)
		rh_status
		;;
	condrestart|try-restart)
		rh_status_q || exit 0
		restart
		;;
	*)
		echo $"Usage $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
		exit 2
esac
exit $?
